package com.hubei.car.handler;

import cn.hutool.core.exceptions.ExceptionUtil;

import com.hubei.car.constant.StatusCode;
import com.hubei.car.entity.Result;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理器
 * @author luokangtao
 * @create 2019-07-15 2:06
 */
@ControllerAdvice //@ControllerAdvice是controller的一个辅助类，最常用的就是作为全局异常处理的切面类
@Slf4j
public class BaseExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result error(Exception e){
        String message = ExceptionUtil.getMessage(e);
        log.info("异常信息message:{}",message);
        String lineString = ExceptionUtil.stacktraceToOneLineString(e);
        log.info("异常信息stacktraceToOneLineString:{}",lineString);
        return new Result(false, StatusCode.ERROR,lineString);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Result methodArgumentNotValidException(Exception e){
        String message = ExceptionUtil.getMessage(e);
        log.info("异常信息message:{}",message);
        String lineString = ExceptionUtil.stacktraceToOneLineString(e);
        log.info("异常信息stacktraceToOneLineString:{}",lineString);
        //处理校验信息
        int mess = message.lastIndexOf("default message");
        int length = "default message".length();
        String substring = message.substring(mess + length, message.length()-2);
        return new Result(false, StatusCode.ERROR,substring);
    }

    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public Result baseException(Exception e){
        String message = ExceptionUtil.getMessage(e);
        //BaseException: 未授权的访问
        log.info("自定义异常信息message:{}",message);
        //com.luokangtao.common.handler.BaseException: 未授权的访问 at com.luokangtao.common.intercept.UserAuthInterceptor.preHandle(UserAuthInterceptor.java:66)
        String lineString = ExceptionUtil.stacktraceToOneLineString(e);
        log.info("自定义异常信息stacktraceToOneLineString:{}",lineString);
        if(((BaseException) e).getStatusCode()>0){
            return new Result(false,((BaseException) e).getStatusCode(),e.getMessage());
        }
        return new Result(false, StatusCode.ERROR,e.getMessage());
    }

    @ExceptionHandler(value = ExpiredJwtException.class)
    @ResponseBody
    public Result expiredJwtException(Exception e){
        String lineString = ExceptionUtil.stacktraceToOneLineString(e);
        log.info("异常信息stacktraceToOneLineString:{}",lineString);
        return  new Result(false,StatusCode.EXPIRED,"登陆失效,请重新登陆");
    }

}
